//
//  ChatTableViewController.m
//  高仿萝卜书摘
//
//  Created by 谢俊逸 on 2016/11/24.
//  Copyright © 2016年 谢俊逸. All rights reserved.
//
#import <ChatKit/LCChatKit.h>
#import "NSObject+LCCKHUD.h"
#import "LCChatKitExample.h"
#import "LCCKContactManager.h"
#import "LCChatKitExample+Setting.h"
#import "ChatTableViewController.h"
#import "XJYHeader.h"
#import "MessageTableViewCell.h"
#import "LCCKLoginViewController.h"
#import "User.h"
#import "XJYMessageViewController.h"

NSNumber *conversationNumber;
NSArray *conversationArray;

@interface ChatTableViewController ()<XJYMessageViewControllerDelegate>




@property (nonatomic,strong) AVIMClient *client;
@property (nonatomic,strong) AVIMConversationQuery *query;
@property (nonatomic,strong) NSArray *array;
@end
static NSString *const MessageCellID = @"MessageCellID";

@implementation ChatTableViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    conversationNumber = [NSNumber numberWithInteger:0];

    [self queryConversationList];
    //在放回的过程中逐渐取消选中状态的
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
    [self registerCell];
    
    
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)registerCell{
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MessageTableViewCell class]) bundle:nil] forCellReuseIdentifier:MessageCellID];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return conversationNumber.unsignedLongValue;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MessageCellID forIndexPath:indexPath];
    
//  从conversation cell信息
    AVIMConversation *conversation = conversationArray[indexPath.row];
    
    NSArray *members = conversation.members;
    [members enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![members[idx] isEqualToString:_client.clientId]) {
            cell.nameLabel.text = members[idx];
        }
    }];
//    cell.nameLabel.text = conversation.conversationId;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"selected");

    XJYMessageViewController *vc = [XJYMessageViewController messagesViewController];
    //从conversation 获得title
    AVIMConversation *conversation = conversationArray[indexPath.row];
    NSArray *members = conversation.members;
    [members enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![self.client.clientId isEqualToString:members[idx]]) {
            vc.title = members[idx];
        }
    }];
    vc.delegateModal = self;
    vc.conversation = conversation;
    UINavigationController *nc = [[UINavigationController alloc]initWithRootViewController:vc];
    [self presentViewController:nc animated:YES completion:nil];

}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{

}


- (NSArray *)allPersonIds {
    NSArray *allPersonIds = [[LCCKContactManager defaultManager] fetchContactPeerIds];
    return allPersonIds;
}



#pragma mark ChatKit
- (void)queryConversationList{
    NSLog(@"self client %@",self.client.clientId);
    [self.client openWithCallback:^(BOOL succeeded, NSError *error) {
        AVIMConversationQuery *query = [self.client conversationQuery];
        [query findConversationsWithCallback:^(NSArray *objects, NSError *error) {
        
            conversationNumber = [NSNumber numberWithUnsignedInteger:[objects count]];
            NSLog(@"找到%ld个对话",[objects count]);
            conversationArray = objects;
            _array = objects;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }];
    }];
    

}

#pragma mark 懒加载
- (AVIMClient *)client{
    if (!_client) {
        NSUserDefaults *standUserDefaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *userData = [standUserDefaults objectForKey:kLoginUserDict];
        _client = [[AVIMClient alloc]initWithClientId:userData[@"name"]];
    }
    return _client;
}

- (AVIMConversationQuery *)query{
    return _query = [self.client conversationQuery];
}

#pragma mark Observation



#pragma mark - AVIMClientDelegate

// 接收消息的回调函数
- (void)conversation:(AVIMConversation *)conversation didReceiveTypedMessage:(AVIMTypedMessage *)message {
    NSLog(@"%@", message.text); 
}


#pragma mark - Demo delegate

- (void)didDidmissXJYMessageViewController:(XJYMessageViewController *)vc
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
